package com.gill.touka.feign.inteceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign的请求拦截器：拦截所有feign的RPC，为所有请求添加token
 */
@Slf4j
public class TokenRelayFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("执行拦截器：TokenRelayFeignInterceptor");
        // 1、获取token
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("X-Token");
        // 2、传递token
        if(StringUtils.isNotBlank(token)){
            requestTemplate.header("X-Token", token);
        }
    }
}
